<template>
  <view class="container">
    <view class="subject">
      <text>学科：</text>
      <radio-group @change="subject_change">
        <label v-for="(item, index) in subjectList" :key="index">
          <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
          {{ item.name }}
        </label>
      </radio-group>
    </view>
    <view class="has_applied">
      <text>是否申请过</text>
      <radio-group @change="apply_type_change">
        <label v-for="(item, index) in revisable_apply_select_list" :key="index">
          <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
          {{ item.name }}
        </label>
      </radio-group>
    </view>
    <view class="card-list">
      <uni-card v-for="(item, index) in questionList" :key="index" :title="item.reference" class="card-item"
        @click="onclickCard(item)" :extra="item.status">
        <view class="card_content">
          <text class="expiration">截止日期：{{ item.expiration.slice(0, 10) }}</text>
          <rich-text :nodes="item.content.slice(0, 42)" space="nbsp">{{ item.order }} .{{
            item.content.slice(0, 30)
          }}</rich-text>
        </view>
      </uni-card>
    </view>
    <uni-popup ref="popup" type="dialog">
      <uni-popup-dialog cancelText="取消" confirmText="申请" message="您确定申请该试卷的上传权限吗？" type="success" title="申请权限"
        content="您确定申请该试卷的上传权限吗？" :duration="2000" :before-close="true" @close="onClosePopup"
        @confirm="onConfirmPopup"></uni-popup-dialog>
    </uni-popup>
  </view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { SelectTypeItem, SubjectItem, QuestionVideoPermitItem } from '@/types/home'
import { postQuestionVideoPermitAPI, getQuestionVideoPermitAPI } from '@/services/home'
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'

// 通用变量
const state = reactive({
  select_question_id: 0,
  subject_id: 1,
  applied_type: 2,
  page: 1,
  size: 10,
  total: 1,
})
// 弹窗
const popup = ref()
// 弹窗关闭处理事件
const onClosePopup = () => {
  popup.value.close()
}
// 弹窗确定事件, 申请录入试卷的权限，并刷新当前的试卷列表
const onConfirmPopup = () => {
  console.log('点击了确定', state.select_question_id)
  postPerimit()
  popup.value.close()
  getQuestionVideoPermitData()
}
// 显示到页面的可录入的试卷，且未过期
const questionList = ref<QuestionVideoPermitItem[]>([])
const questionListId = ref<number[]>([])
// 可录入试卷的是否申请过选择框选项
const revisable_apply_select_list = ref<SelectTypeItem[]>([
  { name: '已申请', value: '1', checked: false },
  { name: '未申请', value: '2', checked: true },
  { name: '已批准', value: '3', checked: false },
])
// 可选择的学科选项
const subjectList = ref<SubjectItem[]>([
  { name: '信息', value: '1', checked: true },
  { name: '通用', value: '2', checked: false },
  { name: '职高', value: '3', checked: false },
])
// 根据学科、不同申请类型获取题目列表
const getQuestionVideoPermitData = async () => {
  const data = {
    applied_type: state.applied_type,
    subject_id: state.subject_id,
    page: state.page,
    size: state.size,
  }
  const res = await getQuestionVideoPermitAPI(data)
  console.log('获取申请试题：', res)
  if (res.code == 200) {
    questionList.value = res.data.results
    // questionListId.value = questionList.value.map((question) => question.id)
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 学科改变了,重新获取该学科的知识点
const subject_change = (e: any) => {
  console.log('学科改变：', e.target.value)
  state.page = 1
  state.subject_id = e.target.value
  getQuestionVideoPermitData()
}
// 选择了不同状态
const apply_type_change = (e: any) => {
  console.log('申请状态改变了', e.target.value)
  state.applied_type = e.target.value
  state.page = 1
  getQuestionVideoPermitData()
}
// 发送申请试卷允许录入权限
const postPerimit = async () => {
  // if (questionListId.value.includes(state.select_question_id)) {
  //   uni.showToast({ icon: 'error', title: '你已经申请过了' })
  //   return 0
  // }
  const data = {
    question: state.select_question_id,
  }
  const res = await postQuestionVideoPermitAPI(data)
  console.log('提交申请解析权限', res)
  if (res.code === 200) {
    uni.showToast({ icon: 'success', title: '提交成功' })
  } else if (res.code === 1022) {
    uni.showToast({ icon: 'error', title: '你已经申请过，联系管理员审批' })
  } else {
    uni.showToast({ icon: 'error', title: '提交错误' })
  }
}
// 点击卡片事件，如果是用户申请过的，则进入第二步页面具体试题；否则进入申请页面
const onclickCard = (question: QuestionVideoPermitItem) => {
  console.log('点击卡片页面', question)
  state.select_question_id = question.id
  if (question.status == '未申请') {
    console.log('未申请，现在去申请', question.id)
    popup.value.open()
  } else if (question.status == '申请过') {
    console.log('管理员未审批', question.id)
    uni.showToast({ icon: 'error', title: '管理员未审批' })
  } else if (question.status == '已批准') {
    uni.navigateTo({
      url: `step_two_upload_video?question=` + encodeURIComponent(JSON.stringify(question)),
    })
  }
}
// 添加更多可录入试题列表，且未过期，用于上拉触底新增数据
const addMorePeimitQuestionVideoData = async () => {
  const data = {
    applied_type: state.applied_type,
    subject_id: state.subject_id,
    page: state.page + 1,
    size: state.size,
  }
  const res = await getQuestionVideoPermitAPI(data)
  console.log('获取更多试题', res)
  if (res.code == 200) {
    questionList.value.push(...res.data.results)
    state.page += 1
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '触底添加数据失败' })
  }
}
// 页面加载
onLoad(async () => {
  getQuestionVideoPermitData()
})
// 自定义下拉刷新被触发
onPullDownRefresh(async () => {
  state.page = 1
  await Promise.all([getQuestionVideoPermitData()])
  // 停止页面加载动画
  setTimeout(() => {
    uni.stopPullDownRefresh()
  }, 1000)
})
// 自定义触底加载更多数据
onReachBottom(async () => {
  if (questionList.value.length >= state.total) {
    uni.showToast({ title: '没有更多数据了！', icon: 'none' })
  } else {
    await Promise.all([addMorePeimitQuestionVideoData()])
  }
})
</script>
<style lang="scss" scoped>
.card_content {
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;
}

.container {
  font-size: 28rpx;
}

.subject,
.has_applied {
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: left;
}
</style>